package com.ljx.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.common.AppHttpCodeEnum;
import com.ljx.common.ResponseResult;
import com.ljx.domain.dto.UserDto;
import com.ljx.domain.entity.Role;
import com.ljx.domain.entity.User;
import com.ljx.domain.entity.UserRole;
import com.ljx.domain.vo.PageVo;
import com.ljx.domain.vo.RoleVo;
import com.ljx.domain.vo.UserInfoVo;
import com.ljx.exception.SystemException;
import com.ljx.mapper.UserMapper;
import com.ljx.service.RoleService;
import com.ljx.service.UserRoleService;
import com.ljx.service.UserService;
import com.ljx.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-04-19 16:58:40
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Override
    public ResponseResult getUser() {
        Long userId = SecurityUtils.getUserId();
        User byId = getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(byId,userInfoVo);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult updateUser(User user) {
        updateById(user);
        return ResponseResult.okResult("修改个人信息成功");
    }

    @Override
    public ResponseResult register(User user) {
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        //...
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        save(user);
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult listAll(Integer pageNum, Integer pageSize, String userName,
                                  String phonenumber, String status) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(userName),User::getUserName,userName);
        lambdaQueryWrapper.eq(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber);
        lambdaQueryWrapper.eq(StringUtils.hasText(status),User::getStatus,status);
        Page<User> page = new Page(pageNum,pageSize);
        page(page,lambdaQueryWrapper);
        PageVo pageVo = new PageVo(page.getRecords(), page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getUserOne(Long id) {
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleService.list(lambdaQueryWrapper);
        List<Long> roleIds = userRoles.stream().map(userRole ->
                userRole.getRoleId()).collect(Collectors.toList());
        List<Role> roles = roleService.list();
        User user = getById(id);
        RoleVo roleVo = new RoleVo(roleIds, roles, user);
        return ResponseResult.okResult(roleVo);
    }

    @Override
    public void saveUser(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        save(user);
        List<Long> roleIds = userDto.getRoleIds();
        if(roleIds != null && roleIds.size() > 0){
            Long userId = user.getId();
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleService.save(userRole);
            }
        }
        return;
    }

    @Override
    public void updateUserById(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        updateById(user);
        Long id = user.getId();
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        userRoleService.remove(queryWrapper);
        List<Long> roleIds = userDto.getRoleIds();
        if(roleIds != null && roleIds.size() > 0){
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(id);
                userRole.setRoleId(roleId);
                userRoleService.save(userRole);
            }
        }
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getNickName,nickName);
        int count = count(lambdaQueryWrapper);
        if(count > 0 )return true;
        else return false;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,userName);
        int count = count(lambdaQueryWrapper);
        if(count > 0) return true;
        else return false;
    }


}
